package com.hcj.springcloud.MyThreadExample.thread;

import java.util.Random;
import java.util.concurrent.*;

/**
 * Created by xxx on 2016/3/20.
 * 启动10个线程，哪个先运行完就返回那个结果
 */
public class CompletionServiceTest {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(10);
        CompletionService completionService = new ExecutorCompletionService(executor);
        for (int i =1; i <=10; i ++) {
            final  int result = i;
            completionService.submit(new Callable() {
                public Integer call() throws Exception {
                    Random random = new Random();
                    Thread.sleep(random.nextInt(10)*(1000));
                    return result;
                }
            });
        }
        Future poll = completionService.poll();
        Future<Integer> take = completionService.take();
        System.out.println(take.get());
        System.out.println(poll.get());
        if(take.isDone()){
            System.out.println("take is done:"+take.get());
        }
        executor.shutdown();
    }
}
